package yiran.stock;

import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import yiran.stock.command.BuyManager;
import yiran.stock.data.DatabaseManager;
import yiran.stock.lang.LangHelper;
import yiran.stock.lister.EventListener;
import yiran.stock.output.Logger;

public final class Stock extends JavaPlugin {
    private StockManager stockManager;
    private EconomyManager economyManager;
    private ConfigManager configManager;
    private BuyManager buyManager;

    @Override
    public void onEnable() {
        Logger.init(this);

        configManager = new ConfigManager(this);
        configManager.loadConfig();

        LangHelper.init(this);

        DatabaseManager.connect(this);

        stockManager = new StockManager(this);
        stockManager.initialize();
        stockManager.start();

        economyManager = new EconomyManager(this);
        economyManager.setupEconomy();

        StockCommand stockCommand = new StockCommand(this);
        this.getCommand("stock").setExecutor(stockCommand);
        this.getCommand("stock").setTabCompleter(stockCommand);

        GuiManager.register(this);
        Bukkit.getPluginManager().registerEvents(
                new EventListener(
                        configManager.getGuiOpenItem(),
                        stockManager,
                        this // 传递插件实例
                ),
                this
        );
        buyManager = new BuyManager();
        Logger.printBanner();
        Logger.info("插件已启动");
    }

    @Override
    public void onDisable() {
        if (stockManager != null) {
            stockManager.stop();
        }

        if (DatabaseManager.getDbType() == DatabaseManager.DatabaseType.SQLITE) {
            configManager.createBackup();
        }

        DatabaseManager.disconnect();
        Logger.info("插件已关闭");
    }

    public StockManager getStockManager() {
        return stockManager;
    }

    public Economy getEconomy() {
        return economyManager.getEconomy();
    }

    public boolean isEconomyEnabled() {
        return !economyManager.isEconomyEnabled();
    }

    @Override
    public void reloadConfig() {
        super.reloadConfig();

        if (configManager != null) {
            configManager.loadConfig();
        }

        if (!DatabaseManager.isConnectionValid()) {
            DatabaseManager.connect(this);
        }
    }

    public BuyManager getBuyManager() {
        return buyManager;
    }
}


